package com.mt.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.mt.config.AliPayConfig;
import com.mt.constants.Result;
import com.mt.feign.OrderApiProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author Wang
 * @Description 支付控制类
 * @date 2020/12/28-8:54
 */
@Controller
public class AliPayController {
    @Resource
    OrderApiProvider orderApiProvider;

    @ResponseBody
    @RequestMapping("/notify")
    public String payNotify(){
        return "notify";
    }


    @RequestMapping("/return")
    public String payReturn(HttpServletRequest request){
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            try {
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            params.put(name, valueStr);
        }
        //调用SDK验证签名
        boolean signVerified = false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, AliPayConfig.alipay_public_key, AliPayConfig.charset,AliPayConfig.sign_type);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        //验证签名
        if(signVerified) {
            //此处编写具体需要实现的业务逻辑
            String orderId = params.get("out_trade_no");
            Result result = orderApiProvider.confirmPayOrder(orderId);
        }
        return "redirect:localhost:8080";
    }

    @ResponseBody
    @GetMapping(value ="/pay",produces = "text/html; charset=UTF-8")
    public String alipayOrder(@RequestParam("orderId") String orderId,
                              @RequestParam("payment") String payment) throws AlipayApiException {

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.gatewayUrl,
                AliPayConfig.app_id,
                AliPayConfig.merchant_private_key,
                "json",
                AliPayConfig.charset,
                AliPayConfig.alipay_public_key,
                AliPayConfig.sign_type);

        //设置请求参数
      //  String payType = alipayOrderRequest.getPayType();
       // System.out.println(alipayOrderRequest.toString());
        // wap
        AlipayTradeWapPayRequest alipayWapRequest = new AlipayTradeWapPayRequest();
        alipayWapRequest.setReturnUrl(AliPayConfig.return_url);
        alipayWapRequest.setNotifyUrl(AliPayConfig.notify_url);

      /*  AlipayTradePagePayRequest alipayPageRequest = new AlipayTradePagePayRequest();
        alipayPageRequest.setReturnUrl(AliPayConfig.return_url);
        alipayPageRequest.setNotifyUrl(AliPayConfig.notify_url);*/

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orderId;
        //付款金额，必填
        String total_amount = payment;
        //订单名称，必填
        String subject = "测试订单";
        //商品描述，可空
        //String body = alipayOrderRequest.getWIDbody();

        //拼接参数
//        alipayPageRequest.setBizContent("{\"out_trade_no\":\""+ 123456 +"\","
//                + "\"total_amount\":\""+ 30 +"\","
//                + "\"subject\":\""+ 123 +"\","
//               // + "\"body\":\""+ body +"\","
//                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //拼接参数
        alipayWapRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                // + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        // 发起请求
        AlipayTradeWapPayResponse response = alipayClient.pageExecute(alipayWapRequest);
        return response.getBody();
    }

    @ResponseBody
    @GetMapping(value ="epay/{orderId}/{payment}",produces = "text/html; charset=UTF-8")
    public String aliEasyPayOrder(@PathVariable("orderId") String orderId,
                              @PathVariable("payment") String payment) throws AlipayApiException {
        return "2";
    }

}
